# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: read_util.py
# Time: 10:52
import sys
import os

sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(""))))
import json
from configparser import ConfigParser

import yaml
from xlrd import open_workbook

from common.utils.file_util import get_real_ini_dir, \
    get_data_yaml, get_data_json, get_data_excel


class MyConfigParser(ConfigParser):
    # 重写configparser中的optionxform函数，解决 ini文件中的建option自动转为小写的问题
    def optionxform(self, optionstr):
        "Rewrite without lower()"
        return optionstr


class OperationIni():
    def __init__(self, filename):
        self.file_path = get_real_ini_dir(filename)
        self.config = MyConfigParser()
        self.config.read(self.file_path, encoding="utf-8")

    def get_own_ini(self):
        '''
        读取ini文件所有节点信息
        :return: 返回整个ini文件的字节信息，如没有数据则返回空字典
        '''
        dict_data = dict()
        for item in self.config.items():
            temp_dict = dict()
            if item[0] == "DEFAULT":
                continue
            line = self.config.items(item[0])
            temp_dict[item[0]] = dict(line)
            dict_data.update(temp_dict)
        return dict_data

    def get_ini_file_path_section_data(self, section_name):
        '''
        读取ini配置文件指定节点信息
        :param section_name:节点名称
        :return:返回ini文件中指定节点信息，当文件不存在或没有数据时返回空字典：{}
        '''

        dict_data = {}
        if self.config.has_section(section_name):
            options = self.config.options(section_name)
            for option in options:
                kv_dict = {}
                item = self.config.get(section_name, option)
                kv_dict[option] = item
                dict_data.update(kv_dict)
            return dict_data
        else:
            return {}

    def get_sections(self):
        '''获取所有section，并以列表形式返回'''
        return self.config.sections()

    def set_value(self, section, option, value):
        '''
        往ini文件中添加&修改键值对，分类必须存在
        :param section: 分类
        :param option: 键
        :param value: 值
        :return: 返回添加
        '''
        try:
            self.config.set(section, option, value)
            with open(self.file_path, "w+") as f:
                return self.config.write(f)
        except Exception as e:
            raise e

    def add_section(self, title):
        '''
        往ini文件中添加分类
        :param title: 分类名称
        :return:
        '''
        try:
            if title not in self.get_sections():
                self.config.add_section(title)
                with open(self.file_path, "w+")as f:
                    return self.config.write(f)
            else:
                print("该分类已存在，不需要重复添加")
        except Exception as e:
            raise e


class OperationYaml():
    def __init__(self, filename):
        self.file_path = get_data_yaml(filename)

    def get_own_yaml(self):
        '''
        获取所有yaml文件中数据
        :return: 使用json格式返回
        '''
        with open(self.file_path, encoding="utf-8") as f:
            return yaml.safe_load(f)

    def write_yaml_file(self, data):
        '''
        往yaml文件中写入数据
        :param data: 要写入的数据
        :return:
        '''
        with open(self.file_path, mode='a', encoding="utf-8") as f:
            yaml.dump(data, stream=f, allow_unicode=True)


class OperationJson():
    def get_own_json(self, filename):
        '''读取json文件中所有内容'''
        file_path = get_data_json(filename)
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return data

    def write_json_file(self, filename, data):
        '''
        写入数据到json文件中
        :param filename: 文件
        :param data: 要写入的数据
        :return: 返回写入之后的数据
        '''
        file_path = get_data_json(filename)
        with open(file_path, "w+", encoding="utf-8") as f:
            json.dump(data, fp=f, ensure_ascii=False)

    def redact_json(self, file_path, information):
        file = get_data_json(file_path)
        with open(file, "r+", encoding="utf-8") as jsonFile:
            data = json.load(jsonFile)
            data["promoter"]["Authorization"] = information
            jsonFile.seek(0)
            json.dump(data, jsonFile, ensure_ascii=False)
            jsonFile.truncate()

class OperationExcel():
    def __init__(self, filename, sheet_id=0):
        self.file_path = get_data_excel(filename)
        self.sheet_id = sheet_id
        self.workbook = open_workbook(self.file_path).sheet_by_index(self.sheet_id)

    # todo Excel表读写完成，等到写完用例之后再继续写
    def get_own_excel(self):
        """
        获取sheet下的所有数据
        :return: 返回sheet下的所有数据
        """
        cls = []
        for i in range(self.workbook.nrows):
            cls.append(self.workbook.row_values(i))
        return cls

    def get_lines(self):
        """
        获取单元格行数
        :return: 返回单元格行数
        """
        return self.workbook.nrows

    def get_value(self, row, col):
        """
        获取单元格数据
        :param row: 行
        :param col: 列
        :return: 返回数据
        """
        return self.get_own_excel()[row][col]


if __name__ == '__main__':
    # print(OperationIni("setting.ini").get_ini_file_path_section_data("host").get("proposer_pass"))
    print(OperationJson().get_own_json("promoter_test.json")["promoter_submit"])